package com.example.hospital.service;

import com.example.hospital.common.PageResponse;
import com.example.hospital.domain.entity.IndicatorResult;
import com.example.hospital.mapper.IndicatorResultMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IndicatorResultService {
    private final IndicatorResultMapper indicatorResultMapper;

    public IndicatorResultService(IndicatorResultMapper indicatorResultMapper) {
        this.indicatorResultMapper = indicatorResultMapper;
    }
    /**
     * 创建指标结果
     * @param result
     * @return
     */
    public IndicatorResult create(IndicatorResult result) { indicatorResultMapper.insert(result); return indicatorResultMapper.findById(result.getResultId()); }
    /**
     * 更新指标结果异常标志与医生备注
     * @param resultId
     * @param abnormalFlag
     * @param doctorComment
     * @return
     */
    public boolean updateFlagAndComment(Long resultId, Boolean abnormalFlag, String doctorComment) { return indicatorResultMapper.updateFlagAndComment(resultId, abnormalFlag, doctorComment) > 0; }
    /**
     * 更新指标结果结果值与异常标志与医生备注
     * @param resultId
     * @param resultValue
     * @param abnormalFlag
     * @param doctorComment
     * @return
     */
    // 新增：允许更新结果值（同时可更新异常标志与医生备注）
    public boolean updateValueFlagComment(Long resultId, String resultValue, Boolean abnormalFlag, String doctorComment) {
        return indicatorResultMapper.updateValueFlagComment(resultId, resultValue, abnormalFlag, doctorComment) > 0;
    }
    /**
     * 分页查询指标结果（按样本ID、指标ID、异常标志筛选）
     * @param sampleId
     * @param indicatorId
     * @param abnormalFlag
     * @param page
     * @param size
     * @return
     */
    public PageResponse<IndicatorResult> list(Long sampleId, Long indicatorId, Boolean abnormalFlag, int page, int size) {
        int offset = (page - 1) * size;
        List<IndicatorResult> list = indicatorResultMapper.list(sampleId, indicatorId, abnormalFlag, size, offset);
        long total = indicatorResultMapper.count(sampleId, indicatorId, abnormalFlag);
        return PageResponse.of(total, page, size, list);
    }
    /**
     * 分页查询用户或订单下的指标结果（按异常标志筛选）
     * @param userId
     * @param orderId
     * @param page
     * @param size
     * @return
     */
    public PageResponse<IndicatorResult> listByUserOrOrder(Long userId, Long orderId, int page, int size) {
        int offset = (page - 1) * size;
        List<IndicatorResult> list = indicatorResultMapper.listByUserOrOrder(userId, orderId, size, offset);
        long total = indicatorResultMapper.countByUserOrOrder(userId, orderId);
        return PageResponse.of(total, page, size, list);
    }
}